package com.gp.shaw.netty.nio.im;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gp.shaw.netty.nio.im.model.IMMsg;
import com.gp.shaw.netty.nio.im.model.IMOperator;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by asus on 2018/11/3.
 */
public class IMClient {
    private String sendId;
    private String ip;
    private int port;
    private SocketChannel socketChannel;
    private ObjectOutputStream oos;
    private ObjectInputStream ois;
    private Selector selector;
    public IMClient(String ip,int port,String sendId){
        this.ip = ip;
        this.port = port;
        this.sendId = sendId;
    }

    public void start(){
        try {
            selector = Selector.open();
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(ip,port));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
            new Thread(new Runnable(){
                @Override
                public void run() {
                    try {
                        while(true) {
                            int selectNum = selector.select();
                            if(selectNum<=0){
                                continue;
                            }
                            Set<SelectionKey> keys = selector.selectedKeys();
                            if(keys==null||keys.size()<=0){
                                continue;
                            }
                            Iterator<SelectionKey> keysIterator = keys.iterator();
                            while (keysIterator.hasNext()){
                                SelectionKey key = keysIterator.next();
                                if(key.isValid()&&key.isReadable()){
                                    reciveMsg((SocketChannel) key.channel());
                                }
                                keysIterator.remove();
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            System.out.println("已启动");

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void doHandler() throws IOException {

    }

    public void sendMsgToPerson(String targetId,String context){

        IMMsg msg = new IMMsg();
        msg.setOperator(IMOperator.SEND_PERSON);
        msg.setSender(sendId);
        msg.setContent(context);
        msg.setTarget(targetId);
        msg.setTime(System.currentTimeMillis());

        send(msg);
    }

    public void sendMsgToGroup(String targetId,String context){

        IMMsg msg = new IMMsg();
        msg.setOperator(IMOperator.SEND_GROUP);
        msg.setSender(sendId);
        msg.setContent(context);
        msg.setTarget(targetId);
        msg.setTime(System.currentTimeMillis());

        send(msg);
    }

    public void login(){
        System.out.println("登录");
        IMMsg msg = new IMMsg();
        msg.setOperator(IMOperator.LOGIN);
        msg.setSender(sendId);
        msg.setTime(System.currentTimeMillis());
        send(msg);
    }

    public void logout(){

        IMMsg msg = new IMMsg();
        msg.setOperator(IMOperator.LOGOUT);
        msg.setSender(sendId);
        msg.setTime(System.currentTimeMillis());


        send(msg);
    }

    public void addGroup(String groupId){

        IMMsg msg = new IMMsg();
        msg.setOperator(IMOperator.ADD_GROUP);
        msg.setSender(sendId);
        msg.setContent(groupId);
        msg.setTime(System.currentTimeMillis());


        send(msg);
    }

    public void send(IMMsg msg){
        SendMsg.send(socketChannel,msg);
    }

    public void reciveMsg(SocketChannel socketChannel) throws IOException {
        try{
            while(true) {
                List<IMMsg> msgs = ReadMsg.read(socketChannel);
                if(msgs==null||msgs.size()<=0){
                    return;
                }
                for(int i = 0;i<msgs.size();i++) {
                    IMMsg msg = msgs.get(i);
                    System.out.println(msg.getSender() + ":" + msg.getContent());
                }
            }
        }finally {
            close();
        }
    }

    public void close() throws IOException {

        if(oos!=null){
            oos.close();
            oos=null;
        }
        if(ois!=null){
            ois.close();
            ois=null;
        }
    }

}
